#!/bin/bash

#Colors
RED="\033[01;31m"
GREEN="\033[01;32m"
PURPLE="\033[01;35m"
BLUE="\033[01;34m"
YELLOW="\033[01;33m"
NC="\033[00m"
#Formats
INFO="${YELLOW}[INFO]${NC}"
WARN="${BLUE}[WARN]${NC}"
ERROR="${RED}[ERROR]${NC}"

CURR_PATH=$(realpath $0)
DIR_PATH=$(dirname ${CURR_PATH})
LOCAL_PATH="file://${DIR_PATH}/"

export ROSDISTRO_INDEX_URL="${LOCAL_PATH}rosdistro/index-v4.yaml"
export ROSDEP_SOURCE_PATH=${DIR_PATH}/rosdistro/rosdep/sources.list.d

usage() {
    cat <<EOF
This script solves the network issue when using `rosdep update` command. 

Syntax: ./rosdep_fix.sh [-h|-i|-u]

OPTIONS:
    -h, --help                 Show this message
    -i, --init                 Initialize ROSDEP.
    -u, --update               Update ROSDEP.
EOF
    exit
}

# Don't display pushd/popd stack
pushd() {
    command pushd "$@" >/dev/null
}

popd() {
    command popd "$@" >/dev/null
}


clone_repo() {
    echo -e "${INFO} Cloning ${GREEN}rosdistro${NC} to local disk..."
    git clone --depth=1 -b master https://hub.fastgit.org/ros/rosdistro.git
}

replace_path() {
    echo -e "${INFO} Re-direct ${GREEN}rosdep${NC} source path to local cache..."

    sed -i s\#https://raw.githubusercontent.com/ros/rosdistro/master/\#${LOCAL_PATH}rosdistro/\# ${DIR_PATH}/rosdistro/rosdep/sources.list.d//20-default.list

    sudo sed -i '/gbpdistro/s/^/#/g' ${DIR_PATH}/rosdistro/rosdep/sources.list.d//20-default.list
}

update() {
    echo -e "${INFO} Updating rosdep..."
    OSDISTRO_INDEX_URL="${LOCAL_PATH}rosdistro/index-v4.yaml" ROSDEP_SOURCE_PATH=${DIR_PATH}/rosdistro/rosdep/sources.list.d rosdep update
}

init() {
    echo -e "${INFO} Initializing rosdep..."
    ROSDISTRO_INDEX_URL="${LOCAL_PATH}rosdistro/index-v4.yaml" ROSDEP_SOURCE_PATH=${DIR_PATH}/rosdistro/rosdep/sources.list.d sudo rosdep init
}


while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
    -h | --help)
        usage
        exit
        ;;
    -i | --init)
        clone_repo
        replace_path
        init
        exit
        ;;
    -u | --update)
        clone_repo
        replace_path
        update
        exit
        ;;
    :)
        echo -e "${ERROR} Missing argument"
        usage
        exit
        ;;
    *)
        echo -e "${ERROR} Unknown option \"$key\""
        usage
        exit
        ;;
    esac
done